class Uv < Formula
  desc "Extremely fast Python package installer and resolver, written in Rust"
  homepage "https://github.com/astral-sh/uv"
  url "https://github.com/astral-sh/uv/archive/refs/tags/0.1.45.tar.gz"
  sha256 "0501a922f944156b35e2169a1d8a2f7a5a2de1dfc71a64b97cf260e0fc8b121d"
  license any_of: ["Apache-2.0", "MIT"]
  head "https://github.com/astral-sh/uv.git", branch: "main"

  bottle do
    sha256 cellar: :any,                 arm64_sonoma:   "9b3ef119bca6a3ec831b9cf099a890ea896d0ee7be02dd6b6845621281a85556"
    sha256 cellar: :any,                 arm64_ventura:  "8e1e0bc0a28f48bbe61eab4033b6f8825e14a2c7facab05d74a03fc02e216332"
    sha256 cellar: :any,                 arm64_monterey: "c4798d401135852600b3d348775b10c1b1a7a44d408f10b7a772f652ed00aea1"
    sha256 cellar: :any,                 sonoma:         "7ab175ff07410265331644340267206c21f455c6ef26d396293ca344bcb6ea8e"
    sha256 cellar: :any,                 ventura:        "c35926e329a96f89bcc8aed5e1a020de2d708c3c27fb1e5c045d34bf4977810a"
    sha256 cellar: :any,                 monterey:       "277b4433ecb4c5486feb8d0c85c95b6b4642bfdb79fcc5482430bc1030faa624"
    sha256 cellar: :any_skip_relocation, x86_64_linux:   "81f74ab70216a30c7dbd3b8d0d0f8a490df233245394911d48386e569c0a104d"
  end

  depends_on "pkg-config" => :build
  depends_on "rust" => :build
  depends_on "libgit2"
  depends_on "openssl@3"

  uses_from_macos "python" => :test

  on_linux do
    # On macOS, bzip2-sys will use the bundled lib as it cannot find the system or brew lib.
    # We only ship bzip2.pc on Linux which bzip2-sys needs to find library.
    depends_on "bzip2"
  end

  def install
    ENV["LIBGIT2_NO_VENDOR"] = "1"

    # Ensure that the `openssl` crate picks up the intended library.
    ENV["OPENSSL_DIR"] = Formula["openssl@3"].opt_prefix
    ENV["OPENSSL_NO_VENDOR"] = "1"

    system "cargo", "install", "--no-default-features", *std_cargo_args(path: "crates/uv")
    generate_completions_from_executable(bin/"uv", "generate-shell-completion")
  end

  def check_binary_linkage(binary, library)
    binary.dynamically_linked_libraries.any? do |dll|
      next false unless dll.start_with?(HOMEBREW_PREFIX.to_s)

      File.realpath(dll) == File.realpath(library)
    end
  end

  test do
    (testpath/"requirements.in").write <<~EOS
      requests
    EOS

    compiled = shell_output("#{bin}/uv pip compile -q requirements.in")
    assert_match "This file was autogenerated by uv", compiled
    assert_match "# via requests", compiled

    [
      Formula["libgit2"].opt_lib/shared_library("libgit2"),
      Formula["openssl@3"].opt_lib/shared_library("libssl"),
      Formula["openssl@3"].opt_lib/shared_library("libcrypto"),
    ].each do |library|
      assert check_binary_linkage(bin/"uv", library),
             "No linkage with #{library.basename}! Cargo is likely using a vendored version."
    end
  end
end
